package id.amikom.jogjabankfinder.activity;

import java.util.ArrayList;
import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import id.amikom.jogjabankfinder.GPSHelper;
import id.amikom.jogjabankfinder.JSONHelper;
import id.amikom.jogjabankfinder.R;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.widget.TextView;

public class Navigasi extends FragmentActivity implements LocationListener
{
	private final String		URL	= "http://maps.googleapis.com/maps/api/directions/json?";
	private LatLng				start;
	private LatLng				end;

	private GoogleMap			maps;
	private JSONHelper			json;
	private GPSHelper			gps;
	private LocationManager		locManager;
	private Location			location;
	private Context				context;

	private String				time, jarak, to;
	private TextView			tvTo, tvTime, tvJarak;

	private Marker				markerMyLocation;

	private ProgressDialog		pDialog;
	private ArrayList<LatLng>	directions;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bank_direction);

		tvTo = (TextView) findViewById(R.id.txtToDirection);
		tvTime = (TextView) findViewById(R.id.txtTimeDirection);
		tvJarak = (TextView) findViewById(R.id.txtJarakDirection);

		locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		context = this;

		json = new JSONHelper();
		gps = new GPSHelper(context, locManager, this);
		location = gps.getLocation();
		if (location != null)
		{
			// start = new LatLng(location.getLatitude(),
			// location.getLongitude());
			onLocationChanged(location);
		}

		Bundle bundle = getIntent().getExtras();
		if (bundle != null)
		{
			to = bundle.getString("to");
			start = new LatLng(bundle.getDouble("start_lat"), bundle.getDouble("start_lng"));
			end = new LatLng(bundle.getDouble("end_lat"), bundle.getDouble("end_lng"));
		}

		maps = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapDirection)).getMap();
		maps.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 16));

		markerMyLocation = maps.addMarker(
				new MarkerOptions()
						.position(start)
						.title("Start")
						.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

		maps.addMarker(new MarkerOptions().position(end).title("End"));

		// drawDirection();

		new AsyncTaskNavigasi().execute();

	}

	private void drawDirection()
	{
		tvJarak.setText("Jarak : " + " " + jarak);
		tvTime.setText("Waktu :" + " " + time);
		tvTo.setText("Tujuan : " + to);

		PolylineOptions line = new PolylineOptions().width(3).color(Color.BLUE);

		for (int i = 0; i < directions.size(); i++)
		{
			line.add(directions.get(i));
		}
		maps.addPolyline(line);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			startActivity(new Intent(Navigasi.this, MenuUtama.class));
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	private class AsyncTaskNavigasi extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... params)
		{
			String uri = URL
					+ "origin=" + start.latitude + "," + start.longitude
					+ "&destination=" + end.latitude + "," + end.longitude
					+ "&sensor=true&units=metric";

			directions = new ArrayList<LatLng>();

			JSONObject jObj = json.getJSONFromUrl(uri);

			directions = json.getDirection(jObj);
			time = json.getDuration(jObj);
			jarak = json.getDistance(jObj);

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			pDialog.dismiss();
			runOnUiThread(new Runnable()
			{
				@Override
				public void run()
				{
					// TODO Auto-generated method stub
					drawDirection();
				}
			});
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			pDialog = new ProgressDialog(Navigasi.this);
			pDialog.setMessage("Get Direction....");
			pDialog.setCancelable(true);
			pDialog.show();
		}
	}

	@Override
	public void onProviderDisabled(String provider)
	{
	}

	@Override
	public void onProviderEnabled(String provider)
	{
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras)
	{
	}

	@Override
	public void onLocationChanged(Location location)
	{
		if (markerMyLocation != null)
		{
			markerMyLocation.remove();

			markerMyLocation = maps.addMarker(new MarkerOptions()
					.position(new LatLng(location.getLatitude(),
							location.getLongitude()))
					.title("Posisi anda")
					.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

			maps.animateCamera(CameraUpdateFactory.newLatLngZoom(new
					LatLng(location.getLatitude(), location.getLongitude()),
					14));
		}
	}

	@Override
	protected void onStart()
	{
		super.onStart();
	}

	@Override
	protected void onStop()
	{
		super.onStop();
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();
	}

	@Override
	protected void onResume()
	{
		super.onResume();
	}

}
